// app/service/user.js
const { Service } = require('egg');

class GoodTypeService extends Service {
  async find(opts) {
    const opts_max = opts.where;

    let maxCount = await this.app.mysql.count('good_type', opts_max);
    let result = await this.app.mysql.select('good_type', opts);
    result.maxCount = maxCount;

    return result;
  }

  async add(goodsInfo) {
    //插入前先检查code 是否唯一
    const goods = await this.app.mysql.get('good_type', {name: goodsInfo.name});

    if( goods && goods.id ){
        return -2;
    }

    const result = await this.app.mysql.insert('good_type', goodsInfo);

    return result.affectedRows;
  }

  async update(goodsInfo) {
    //更新前先检查数据是否存在
    const goods = await this.app.mysql.get('good_type', {id: goodsInfo.id});
    if( goods && goods.id ){
        const result = await this.app.mysql.update('good_type', goodsInfo);
        return result.affectedRows;
    }else {
        return -1;
    }
  }

  async del(id) {
    const goods = await this.app.mysql.get('good_type', {id});

    if( !goods || !goods.id ){
      return -2;
    }

    const result = await this.app.mysql.delete('good_type', {id});
    
    return result.affectedRows;
  }

  async batchRemove(ids) {
    const arr_ids = ids.split(',');
    const conn = await this.app.mysql.beginTransaction();
  
    try {
      for( let i = 0; i<arr_ids.length; i++ ){
        await this.app.mysql.delete('good_type', {id: arr_ids[i]});
      }
      await conn.commit();
      return 1;
    } catch (err) {
      // error, rollback
      await conn.rollback(); // rollback call won't throw err
      return -1;
    }
  }

}

module.exports = GoodTypeService;